<template>
  <div>
    <a-row :gutter="5">
      <a-col :span="5">
        <a-card :bordered="false" title="商品分类" :headStyle="heightStyle" :body-style="bodyStyle">
          <a-row style="margin-left: 2px">
            <a-button @click="addCategory(0)" type="primary" icon="plus" size="small">父分类</a-button>
            <a-button @click="addCategory(parentId)" v-if="showAddChild" type="primary" icon="plus" size="small">子分类</a-button>

          </a-row>
          <a-tree :treeData="treeData" @select="onSelect"/>
        </a-card>
      </a-col>
      <a-col :span="19">
        <a-card :bordered="false" :tabList="tabListNoTitle" :activeTabKey="noTitleKey" @tabChange="key => onTabChange(key)" :body-style="bodyStyle">
          <div v-show="noTitleKey === 'info'">
            <f-form ref="form" :action="api.category" :form-key="this.formItem.categoryId" @success="onSuccess">
              <f-form-item label="上级分类" type="other" v-if="formItem.parentId!=0">
                <a-tree-select style="width: 300px;" :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }" placeholder='请选择父级分类' v-model="formItem.parentId" :treeData="treeData"/>
              </f-form-item>

              <f-form-item label="分类名称" name="categoryName"  :required="true" :value="formItem.categoryName"/>
              <f-form-item label="排序值" type="number"  data-type="number" :required="true" name="sortOrder" :value="formItem.sortOrder"/>
              <!-- <f-form-item label="状态" name="catagoryState" type="radio"  :data="api.common.showState" :value="formItem.catagoryState"/>-->
              <f-form-item label="分类图标" type="upload" name="categoryIcon" :value.sync="formItem.categoryIcon" :file-max="1"/>
            </f-form>
            <div class="form-footer">

              <a-button type="primary" @click="handleSubmit" :loading="saving" icon="save" :disabled="btnDisabled">保存
              </a-button>
              <a-button title="删除" @click="delCategory" type="default" icon="delete" v-if="formItem.categoryId" >删除
              </a-button>
            </div>
          </div>

          <div v-show="noTitleKey === 'specification'">
            <template v-for="(item,index) in allSpecs">
              <a-card>
                <div slot="title">
                  <a-tooltip placement="topLeft" title="取值示例:基本信息、主体信息、规格、特性等">
                    <a-input style="width: 200px;" v-model="item.group" placeholder="参数分组名称"></a-input>
                  </a-tooltip>
                </div>
                <div slot="extra">
                  <a-icon type="delete" @click="deleteGroup(item,index)"/>
                </div>
                <div :key="index" v-for="(param,index) in item.params" class="rowItem">
                  <a-divider orientation="left" dashed>{{param.k}}</a-divider>
                  <div href="#">
                    <a-input style="width: 150px" size="small" v-model="param.k"></a-input>
                    <a-switch v-model="param.sku" @change.self.prevent="onChange" checkedChildren="是" unCheckedChildren="否" style="margin-left: 10px"/>
                    是否规格
                    <a-switch v-model="param.allowDel" @change.self.prevent="allowDelChange" checkedChildren="是" unCheckedChildren="否" style="margin-left: 10px"/>
                    允许删除
                    <a-switch v-model="param.searchable" @change.self.prevent="searchableChange" checkedChildren="是" unCheckedChildren="否" style="margin-left: 10px"/>
                    查询条件
                    <a-icon type="close" class="close" @click="deleteGroupParams(item.params,index)"/>
                  </div>
                  <div>
                    <template v-for="(item,index) in param.options">
                      <span class="rowOption">
                      <a-input placeholder="默认选项" style="width:150px;margin-top: 5px;margin-right: 5px;" size="small" v-model="item.name">
                        <f-color-picker slot="addonAfter" v-model="item.value" @change="(color)=>headleChangeColor(color,item)" v-if="param.type==1"></f-color-picker>
                      </a-input>
                      <a-icon type="close" @click="() => removeOptions(param,index)" class="closeOption"/>
                      </span>
                    </template>
                    <a-button type="dashed" block size="small" style="margin-top:5px;width:55px;" @click="addOptions(param)">
                      添加
                    </a-button>
                  </div>

                </div>


                <a-divider orientation="left"></a-divider>
                <div>
                  <a-button type="dashed" block style="margin-top: 10px;width:150px;" @click="addGroupParams(item.params)">
                    添加参数项
                  </a-button>
                  <a-button type="dashed" block style="margin-top: 10px;width:150px;" @click="$refs.modal.handleShow(item.params)">
                    选择参数项
                  </a-button>
                </div>

              </a-card>
              <a-divider :dashed="true"></a-divider>
            </template>
            <div>
              <a-button @click="addGroup" :loading="saving" icon="plus">添加参数分组</a-button>
              <a-button type="primary" @click="groupSave" :loading="saving" icon="save">保存</a-button>
            </div>
          </div>
          <specs-select ref="modal"></specs-select>
        </a-card>
      </a-col>
    </a-row>

  </div>
</template>

<script>
  import { listToTree2 } from '@/utils/util'
  import SpecsSelect from './specs_select'

  export default {
    name: 'index',
    components: { SpecsSelect },
    data() {
      return {
        catagoryState: 1,
        saving: false,
        btnDisabled: true,
        activeKey: ['1'],
        parentId: null,
        allSpecs: [],
        showAddChild: false,
        maxCategoryLevel: 3,
        specificationId: 0,
        customStyle: 'background: #f7f7f7;border-radius: 3px;margin-bottom:1px;border: 0;overflow: hidden',
        bodyStyle: {
          minHeight: '600px'
        },
        heightStyle: {
          height: 55
        },
        formItem: {
          categoryId: null,
          categoryName: '',
          sortOrder: 0,
          catagoryState: 1,
          parentId: null
        },
        ttt: '基础参数不',
        tabListNoTitle: [{
          key: 'info',
          tab: '基本信息'
        }],
        noTitleKey: 'info',
        treeData: []
      }
    },
    created() {
      this.loadData()
    },
    methods: {
      onChange(checked) {
        item['sku'] = checked
      },
      allowDelChange(checked) {
        item['allowDel'] = checked
      },
      searchableChange(checked) {
        item['selected'] = []
        item['searchable'] = checked
      },
      onTabChange(key) {
        this.noTitleKey = key
      },
      /**
       * 添加参数组
       */
      addGroup() {
        this.allSpecs.push({
          'id': new Date().getTime(),
          'group': '',
          'allowDel': false,
          'params': []
        })
        console.log(this.allSpecs)
      },
      /**
       * 删除参数组
       */
      deleteGroup(group, index) {
        this.allSpecs.splice(index, 1)
        console.log(this.allSpecs)
      },
      /**
       * 添加参数项目
       */
      addGroupParams(params) {
        console.log(params)
        params.push({
          'id': new Date().getTime(),
          'k': '',
          'searchable': false,
          'type': 2,
          'v': '',
          'allowDel': false,
          'sku': false,
          'options': [],
          'selected': [],
          'numerical': true,
          'unit': ''
        })
      },
      /**
       * 删除参数项
       */
      deleteGroupParams(params, index) {
        params.splice(index, 1)
        console.log(this.allSpecs)
      },
      headleChangeColor(color, item) {
        console.log(item)
        item.name = color.label
      },

      addOptions(params) {
        params.options.push({ name: '', value: '' })
      },
      removeOptions(params, index) {
        params.options.splice(index, 1)
      },
      loadData() {
        this.http.get(this, {
          url: this.api.category.list,
          data: {
            params: {}
          },
          success: function(me, data, extra) {
            let obj = listToTree2(data, {
              primaryKey: 'categoryId',
              titleKey: 'categoryName'
            })
            me.maxCategoryLevel = extra.categoryLevel
            me.treeData = obj
          }
        })
      },
      onSelect(selectedKeys, { node }) {
        this.btnDisabled = false
        this.showAddChild = false
        this.$refs.form.resetFields()
        this.allSpecs = []
        this.specificationId = ''
        this.formItem = node.dataRef
        if (this.formItem.categoryLevel < this.maxCategoryLevel) {
          this.showAddChild = true
        }
        this.parentId = node.dataRef.categoryId
        if (node.dataRef.parentId == 0) {
          this.tabListNoTitle = [{
            key: 'info',
            tab: '基本信息'
          }]
          this.noTitleKey = 'info'
        } else {
          this.tabListNoTitle = [{
            key: 'info',
            tab: '基本信息'
          }, {
            key: 'specification',
            tab: '商品参数规格配置'
          }]
        }
        this.http.get(this, {
          url: this.api.specscategory.getSpecsCategory,
          params: {
            categoryId: this.formItem.categoryId
          },
          success: function(me, data) {
            me.allSpecs = JSON.parse(data.specifications)
            me.specificationId = data.specificationId
            console.log(data)
          }
        })
      },
      onSuccess() {
        this.loadData()
        this.saving = false
      },
      addCategory(parentId) {
        this.http.post(this, {
          url: this.api.category.add,
          data: {
            params: { categoryName: '一级分类', parentId: parentId }
          },
          success: function(me) {
            me.loadData()
          }
        })
      },
      delCategory() {
        this.http.del(this, {
          url: this.api.category.remove,
          data: {
            ids: this.formItem.categoryId
          },
          success: function(me) {
            me.loadData()
            me.btnDisabled = true
          }
        })
      },
      handleSubmit() {
        this.$refs.form.submit({ catagoryState: this.catagoryState, ...this.formItem })
      },
      groupSave() {
        this.http.saveOrUpdate(this, {
          api: this.api.specscategory,
          data: {
            id: this.specificationId,
            params: {
              categoryId: this.formItem.categoryId,
              specifications: JSON.stringify(this.allSpecs)
            }
          }, success: function(me, data) {
            me.specificationId = data.specificationId
          }
        })
      }
    }
  }
</script>
<style scoped lang="less" rel="stylesheet/less">
  .rowItem {
    .close {
      float: right;
      font-size: 15px;
      padding-left: 18px;
    }


  }

  .rowOption {
    .closeOption {
      position: absolute;
      margin-left: -13px;
      font-size: 10px;
      color: #66666;
      display: none;

    }

    &:hover {
      .closeOption {
        display: inline-block;
      }
    }
  }


</style>
